<?php


namespace app\shop\middleware;


use app\Request;

use app\shop\model\user\UserModel;
use app\shop\model\user\UserTokenModel;
use app\shop\service\admin\AdminLogService;


class Auth
{
    /**
     * 认证中间件
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle(Request $request, \Closure $next)
    {
        try {
            $token = $request->header('Authorization');
            if (empty($token)) {
                throw new \Exception('请重新登录', -1);
            }
            $tokenInfo = UserTokenModel::where('token', $token)->find();
            if (empty($tokenInfo)) {
                throw new \Exception('请重新登录', -1);
            }
            if ($tokenInfo['valid_time'] < time()) {
                throw new \Exception('请重新登录', -1);
            }
            $userInfo = UserModel::find($tokenInfo['user_id']);
            if (!$userInfo) {
                throw new \Exception('非法请求', -1);
            }
            $request->withMiddleware(['userId' => $userInfo['user_id']]);
            $request->withMiddleware(['userInfo' => $userInfo]);
            $request->withMiddleware(['token' => $token]);
            AdminLogService::createLog($userInfo['user_id'], $userInfo['realname'], $request->domain(true), $request->pathinfo(),
                $request->param(), $request->method(), $request->ip(), $request->header('user-agent'), $token);
        } catch (\Exception $exception) {
            AdminLogService::createLog(0, '', $request->domain(true), $request->pathinfo(),
                $request->param(), $request->method(), $request->ip(), $request->header('user-agent'), $token, $exception->getMessage());
            return json()->data(['code' => $exception->getCode(), 'msg' => $exception->getMessage(), 'data' => []]);
        }
        return $next($request);
    }
}